﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using System.Data.SqlClient;

namespace Dapper.Repository
{
    public class QueryDbConnection: IDisposable
    {
        private IDbConnection _dbConnection;
        private IOptions<DbSettings> _dbSettings;
        public Guid ConnectionId { get; private set; }
        public QueryDbConnection(IOptions<DbSettings> dbSettings)
        {
            ConnectionId = Guid.NewGuid();
            _dbSettings = dbSettings;
        }
        public IDbConnection DbConnection
        {
            get
            {
                if (_dbConnection == null)
                    _dbConnection = new SqlConnection(_dbSettings.Value.ConnectionString);
                //design: only open when needed.
                if (_dbConnection.State == ConnectionState.Closed)
                    _dbConnection.Open();

                return _dbConnection;
            }
        }
        public void Dispose() {
            if (_dbConnection != null&&_dbConnection.State== ConnectionState.Open) {
                _dbConnection.Close();
                _dbConnection.Dispose();
            }
        }

    }
}
